package client;

import gui.ClientGUI;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.Socket;

import server.MyNapsterProtocol;

public class ClientTransferSocket extends Thread {

	private Socket userSocket;
	private ClientGUI clientGui;

	public ClientTransferSocket(ClientGUI gui, Socket userSocket) {
		clientGui = gui;
		this.userSocket = userSocket;
	}

	public void run() {
		try {
			DataInputStream inputMsg = new DataInputStream(userSocket.getInputStream());  
			DataOutputStream outputMsg = new DataOutputStream(userSocket.getOutputStream());
			
			outputMsg.writeUTF(MyNapsterProtocol.CLIENT_WAITING_FILE);

			//recebe o nome arquivo que o cliente quer baixar e busca o arquivo
			String fileName = inputMsg.readUTF();
			File file = searchFileToUpload(clientGui.getClientSharedFolder(), fileName);
			
			if (file == null || !file.exists()){
				outputMsg.writeUTF(MyNapsterProtocol.FILE_NOT_FOUND);
				return;
			}
			
			DataInputStream input = new DataInputStream(new FileInputStream(file));
			
			outputMsg.writeUTF(MyNapsterProtocol.STARTING_UPLOAD);
			
			byte[] cache = new byte[4096];   
			int size = 0;   
			while ((size = input.read(cache)) > -1) { 
				outputMsg.write(cache, 0, size);
			}

			inputMsg.close();
			outputMsg.close();
			input.close();  
			userSocket.close();  
		}catch (Exception e) {
			clientGui.appendLogMessage(e.getMessage());
		}
	}
	
	/**
	 * Busca um arquivo pelo nome na pasta de arquivos compartilhados
	 * @param fileName
	 * @return
	 */
	private File searchFileToUpload(File path, String fileName) {
		File[] contents = path.listFiles();
		File file = null;
        for (int i=0; i < contents.length; i++) {
            if (contents[i].isDirectory()) {
            	file = searchFileToUpload(contents[i], fileName);
            	if (file != null){
            		return file;
            	}
            } else {
            	if (contents[i].getName().equals(fileName)){
            		return contents[i];
            	}
            }
        }
        return file;
	}

}
